﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Nuane.Posterous
{
	/// <summary>
	/// Represents a file attachment of a new posterous post. An element of <see cref="PosterousNewPost.Files"/>.
	/// </summary>
	public class PosterousFile
	{
		/// <summary>
		/// Gets file info.
		/// </summary>
		/// <value>File info.</value>
		public FileInfo Info { get; private set; }

		/// <summary>
		/// Gets or sets the file name without path.
		/// </summary>
		/// <value>File name.</value>
		public string Name { get; set; }

		/// <summary>
		/// Creates a new instance of a file attachment.
		/// </summary>
		/// <param name="fileName">Path to the file.</param>
		public PosterousFile(string fileName)
		{
			if (fileName == null)
				throw new ArgumentNullException("fileName");

			Info = new FileInfo(fileName);
			Name = Info.Name;
			if (!File.Exists(fileName))
				throw new PosterousException("File does not exist.", PosterousExceptionStatus.OperationFailure);

			if (FileLength > PosterousNewPost.MaxMediaLength)
				throw new PosterousException("File is too long.", PosterousExceptionStatus.OperationFailure);
		}

		/// <summary>
		/// Gets file length.
		/// </summary>
		/// <value>File length.</value>
		public long FileLength
		{
			get { return Info.Length; }
		}

		internal byte[] ReadAll()
		{
			try
			{
				return File.ReadAllBytes(Info.FullName);
			}
			catch (IOException x)
			{
				throw new PosterousException("Unable to read media file.", PosterousExceptionStatus.OperationFailure, x);
			}
			catch (UnauthorizedAccessException x)
			{
				throw new PosterousException("Not authorized to read media file.", PosterousExceptionStatus.OperationFailure, x);
			}
		}
	}
}
